<?php


namespace app\api\controller;


use app\api\validate\User;
use app\common\model\Sms;
use app\common\model\UserException;
use app\common\model\Users;
use think\facade\Db;

class Login extends Base
{

    //用户注册
    public function register()
    {
        $data = input('post.');
        $res = validate(User::class)->check($data);
        if ($res !== true) {
            throw new UserException($res->msg);
        }
        Users::register($data['phone'], $data['yzm'], $data['pass'], $data['invite_code']);
        return $this->response('注册成功');
    }

    //获取验证码
    public function getCode()
    {
        $mobile = $this->essentialParam('mobile');
        $type = $this->essentialParam('type');
        if (!in_array($type, [Sms::SMS_REGISTER, Sms::SMS_PASSWORD, Sms::SMS_LOGIN])) {
            throw new UserException('验证码类型错误');
        }
        $code = Sms::sendCode($mobile, $type, '');
        $this->insertResponse('msg', '验证码发送成功，有效期' . (Sms::EXPIRE_TIME / 60) . '分钟');
        return $this->response('发送成功');

    }

    //用户密码登录
    public function loginPwd()
    {
        $mobile = $this->essentialParam('mobile');
        $password = $this->essentialParam('password');
        $token = Users::loginPwd($mobile, $password);
        $this->insertResponse('token', $token);
        return $this->response('登录成功');
    }

    //用户验证码登录
    public function loginCode()
    {
        $mobile = $this->essentialParam('mobile');
        $code = $this->essentialParam('code');
        $token = Users::loginCode($mobile, $code);
        $this->insertResponse('token', $token);
        return $this->response('登录成功');
    }

    //修改密码
    public function modifyPassword()
    {
        $mobile = $this->essentialParam('mobile');
        $code = $this->essentialParam('code');
        $new_password = $this->essentialParam('new_password');
        $check_res = $this->validate(compact('mobile', 'code', 'new_password'), [
            "mobile|手机号" => "require|mobile",
            "code|验证码" => "require",
            "new_password|新密码" => "require"
        ]);
        if ($check_res !== true) {
            throw new UserException($check_res);
        } else {
            Users::modifyPassword($mobile, $code, $new_password);
        }
        return $this->response('修改成功');
    }


}